﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Meow.Core
{
    public static class Exts
    {
        public static string ToStringInvariant(this int i, string format)
        {
            return i.ToString(format, NumberFormatInfo.InvariantInfo);
        }

        /// <summary>
        /// 结构体数组转byte数组
        /// </summary>
        /// <param name="structObj"></param>
        /// <returns></returns>
        public static byte[] StructArrayToBytes<T>(T[] structObj) where T : struct
        {
            //返回类的非托管大小（以字节为单位）  
            int size = Marshal.SizeOf(typeof(T));

            //分配大小  
            byte[] bytes = new byte[size * structObj.Length];

            //从进程的非托管堆中分配内存给structPtr  
            IntPtr structPtr = Marshal.AllocHGlobal(size * structObj.Length);
            try
            {
                for(var i = 0; i < structObj.Length; i++)
                {
                    //将数据从托管对象structObj封送到非托管内存块structPtr  
                    Marshal.StructureToPtr(structObj[i], structPtr + i * size, false);
                }


                //Marshal.StructureToPtr(structObj, structPtr, true);  
                //将数据从非托管内存指针复制到托管 8 位无符号整数数组  
                Marshal.Copy(structPtr, bytes, 0, size * structObj.Length);

                return bytes;
            }
            finally
            {
                //释放以前使用 AllocHGlobal 从进程的非托管内存中分配的内存  
                Marshal.FreeHGlobal(structPtr);
            }
        }
    }
}
